<?php

namespace App\Http\Controllers\Coin;

use App\Http\Controllers\Controller;
use App\Models\Config;
use Illuminate\Http\Request;
use App\Models\Currency;
use App\Models\Property;
use App\Models\Recharge;
use App\Models\User;
use App\Models\UserAlipay;
use App\Models\UserWechat;
use App\Models\RechOrder;
use App\Library\Yunxin;
use App\Traits\YunXinTrait;
use Exception;
use DB;

/**
 * Created by PhpStorm.
 * User: lizhenhua
 * Date: 2018/3/22
 * Time: 14:05.
 */
class EntryOrdersController extends Controller
{
    use YunXinTrait;

    /**
     * c2c买入和卖出列表.
     * @date 2018/03/22
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function entry_orders(Request $request)
    {
        $info = $request->all();
        if (empty($info['type'])) {
            $user_type = 2;
        } elseif ($info['type'] == 1) {
            $user_type = 2;
        } else {
            $user_type = 1;
        }
        $where['type'] = $user_type;
        $result = RechOrder::where($where)
            ->whereIn('status', [1, 2, 3])
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        if (collect($result)->count() == 0)//接口返回
            return respF(1015);
        $data = [];
        foreach ($result as $key => $value) {
            $data[$key]['nickname'] = $value->user->nickname; //名称
            $data[$key]['photo'] = config('alioss.host') . '/' . $value->user->headimg; //图片
            $data[$key]['oid'] = $value->id; //订单id
            $data[$key]['price_section'] = $value->price_section; //价格
            $data[$key]['is_custom'] = $value->is_custom; //前端判断是否为自定义0为是1位否
            $data[$key]['uid'] = $value->uid; //商家id
            $data[$key]['type'] = $value->type; //买卖类型
        }
        if (collect($data)->count() == 0)
            return respF(1015);
        //接口返回
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * c2c买入和卖出详情.
     * @date 2018/03/22
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
//    public function pay_info(Request $request)
//    {
//        $data = [];
//        $info = $request->all();
//
//        if (empty($info['id'])) {
//            return respF(1003);
//        }
//
//        $result = RechOrder::where(['id' => $info['id']])->get();
//
//        if (count($result) == 0) {
//            return respF(1015);
//        }
//
//        $cid = Currency::where(['is_standard' => 1])->value('id');
//
//        $data = [];
//        foreach ($result as $key => $value) {
//            $data[$key]['min_price'] = $value->min;//可购买的最小值
//            $data[$key]['max_price'] = $value->max;//可购买的最大值
//            $data[$key]['surplus_num'] = sprintf("%.6f", $value->surplus_num);//剩余数量
//            $data[$key]['price'] = $this->handlePrice($value->id);;//单价
//            $data[$key]['bid'] = $value->uid??0;//商家id
//            $data[$key]['type'] = $value->type;//买入和卖出判断
//        }
//
//        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
//    }

    /**
     * c2c买入和卖出提交接口.
     * @date 2018/03/22
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function pay_order(Request $request)
    {
        try {
            if (!$request->has('total_price', 'bid', 'num', 'price', 'id', 'type', 'token'))
                throw new Exception(1000);
            $info = $request->all();
            if (empty($info['total_price']) || empty($info['bid']) || empty($info['num'])
                || empty($info['id']) || empty($info['type']) || empty($info['price']) || empty($info['uid']) || empty($info['token'])
            )//验证参数
                throw new Exception(1003);
            $real = RechOrder::where(['id' => $info['id']])->first();//查找广告单
            if ($real->uid == $info['uid']) //不能购买自己发布的广告
                throw new Exception(3022);
            if ($real->trade_limit == 1) {//验证交易限制(已购买用户购买)
                $trade_order = Recharge::where(['uid' => $info['uid'], 'status' => 3])->first();//平台有过交易的用户(已完成)
                if (collect($trade_order)->count() == 0) //不支持新用户购买
                    throw new Exception(3018);
            }
            if ($real->trade_type == 1) {//验证交易时间
                $trade_time = explode('-', $real->trade_time);//时间区间转为数组
                $now_time = date('H:i', time());//当前时间
                if ($now_time < $trade_time[0] || $now_time > $trade_time[1])//不在区间
                    throw new Exception(3019);//不在商家指定交易时间内//return respF(3019);
            }
            $user = User::find($info['uid']); //查找用户
            if ($user->real_status != 2) //验证用户实名 //实名认证未通过
                throw new Exception(2005);
            if ($info['type'] != $real->type) //return respF(1003);
                throw new Exception(1003);

            //开启事务
            DB::beginTransaction();
            if ($info['type'] == 1) {//type 1 用户卖出 2用户买入
                $pay_pass = User::where(['id' => $info['uid']])->value('pay_pass');
                $type = 2;
                if (md5($info['pay_pass']) != $pay_pass)
                    throw new Exception(2026);
                $usdt_id = Currency::where('name_en', 'USDT')->value('id');//usdt ID
                $property = Property::where(['uid' => $info['uid'], 'cid' => $usdt_id])->first();//用户usdt资产
                if ($property->balance < $info['num']) //判断资产//用户资产不足
                    throw new Exception(2008);
                if (collect($user->user_alipay)->count() == 0 && collect($user->user_wechat)->count() == 0 && collect($user->user_bank)->count() == 0) //判断支付方式
                    throw new Exception(3016);//请绑定至少一种支付方式
                $property->decrement('balance', $info['num']);//冻结用户资产
                $property->increment('blocked', $info['num']);//冻结用户资产
            } else {
                $type = 1;
            }
            if ($real->surplus_num < $info['num'])
                throw new Exception(2034);
            $code = getCode();
            $data_info = [
                'uid' => $info['uid'],
                'order_id' => $info['id'],
                'num' => $info['num'],
                'price' => $info['price'],
                'total_price' => $info['total_price'],
                'bid' => $info['bid'],
                'status' => 1,
                'mark_no' => $code,
                'type' => $type,
                'order_no' => get_microtimes(),
            ];
            $real->decrement('surplus_num', $info['num']);//减去广告单剩余数量
            $real->increment('deal_num', $info['num']);//增加成交数量
            $result = Recharge::create($data_info);//新增法币交易记录
            $id['id'] = $result->id;
            DB::commit();
            return response()->json(['status' => 1, 'msg' => '下单成功', 'data' => $id]);
        } catch (Exception $e) {
            DB::rollback();//回滚
            $msg = $e->getMessage();//接收错误号
            return respF($msg);
        }
    }

    /**
     * c2c订单状态
     * @date 2018/03/24
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function order_info(Request $request)
    {
        $info = $request->all();
        $data = [];
        if (empty($info['oid']))
            return respF(1003);
        $real = Recharge::where('id', $info['oid'])->first(); //查询订单表
        if (collect($real)->count() == 0)
            return respF(1002);
        //商家信息
        $busi = User::where('id', $real->bid)->first();
        $data['business']['nickname'] = $busi->nickname;
        $data['business']['headimg'] = config('alioss.host') . '/' . $busi->headimg;
        $data['business']['bid'] = $busi->id;
        //订单信息
        $data['total_price'] = sprintf('%.2f', $real->total_price); //交易金额
        $data['num'] = sprintf('%.2f', $real->num); //数量
        $data['price'] = sprintf('%.2f', $real->price); //单价
        $data['mark_no'] = $real->mark_no; //参考号
        $data['status'] = $real->status;
        $data['order_no'] = $real->order_no; //订单号
        $data['created_at'] = strtotime($real->created_at); //创建时间
        $data['end_at'] = strtotime($real->created_at)+3600; //结束时间
        $data['now_at'] = time(); //当前时间
        $data['updated_at'] = strtotime($real->updated_at); //修改时间
        $data['type'] = $real->type ?? null;
        $data['genre'] = $this->handle_show_status($real->type, $real->status,2); //订单状态
        $data['phone'] = $real->enters->phone ?? null; //商家电话
        $data['pay_time'] = $real->pay_time ?? null; //付款时间戳
        
        if ($data['type'] == 2) {
            $data['explain'] = Config::where('key','verify_coin')->value('value');
            $alipay = UserAlipay::where(['uid' => $real->uid])->select('alipay_account', 'alipay_code')->first();
            if ($alipay) {
                $data['alipay']['alipay_account'] = $alipay->alipay_account;
                $data['alipay']['alipay_code'] = config('alioss.host') . $alipay->alipay_code;
            } else {
                $data['alipay']['alipay_account'] = '';
                $data['alipay']['alipay_code'] = '';
            }
            $wechat = UserWechat::where(['uid' => $real->uid])->select('wechat_account', 'wechat_code')->first();
            if ($wechat) {
                $data['wechat']['wechat_code'] = config('alioss.host') . $wechat->wechat_code;
                $data['wechat']['wechat_account'] = $wechat->wechat_account;
            }else{
                $data['wechat']['wechat_code'] = '';
                $data['wechat']['wechat_account'] = '';
            }
            $data['alipay']['qr_code'] = $data['alipay']['squeak'] = '';
        } else {
            $data['explain'] = Config::where('key','pay_price')->value('value');
            $data['alipay'] = RechOrder::where(['id' => $real->order_id])->select('squeak', 'qr_code')->first() ?? null;
            $data['alipay']['qr_code'] = config('alioss.host') .$data['alipay']->qr_code;
            $data['alipay']['alipay_code'] = $data['alipay']['alipay_account'] = $data['wechat']['wechat_code'] = $data['wechat']['wechat_account'] = '';
        }
        //增加申述和被申述
        $appeal = $reply = [];
        $appeal['info'] = ['id' => '', 'uid' => '', 'type' => '', 'content' => '', 'status' => '', 'expire_time' => '', 'note' => ''];
        $reply = ['uid' => '', 'content' => '', 'status' => '', 'note' => ''];
        $appeal['imgs'] = [];
        if ($real->appeal_order) {
            $appeal['info'] = $real->appeal_order()->select('id', 'uid', 'type', 'content', 'status', 'expire_time', 'note')->first();
            $imgs = $real->appeal_order->appeal_imgs()->select('img')->get();
            //处理图片
            foreach ($imgs as $img) {
                $img->img = config('alioss.host') .$img->img;
            }
            $appeal['imgs'] = $imgs;
            if (collect($real->appeal_order->appeal_reply)->count() > 0)
                $reply = $real->appeal_order->appeal_reply()->select('uid', 'content', 'status', 'note')->first();
        }
        $data['appeal'] = $appeal;
        $data['reply'] = $reply;
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * c2c订单列表.
     * @date 2018/03/24
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function rechorder_list(Request $request)
    {
        $info = $request->all();
        $data = [];
        if (empty($info['uid']) || empty($info['token']))
            return respF(1003);
        $model = new Recharge();
        if (empty($info['genre']))
            $info['genre'] = 0;
        $where = $model->genre($info['genre'], $info['uid']);
        $result = Recharge::where($where)->where('status', '<>', 4)->orderby('created_at', 'DESC')->paginate(10);
        if ($info['genre'] == 4)
            $result = Recharge::where($where)->whereIn('status', [5, 6])->orderby('created_at', 'DESC')->paginate(10);
        if ($result->count() <= 0)
            return respF(1009);
        foreach ($result as $k => $v) {
            $data[$k]['order_no'] = $v->order_no; //订单号
            $data[$k]['nickname'] = $v->seller->nickname; //名称
            $data[$k]['photo'] = config('alioss.host') . '/' . $v->seller->headimg; //名称
            $data[$k]['oid'] = $v->id; //订单id
            $data[$k]['type'] = $v->type ?? null; //1为用户卖 2为用户买
            $data[$k]['total_price'] = sprintf('%.2f', $v->total_price); //总价
            $data[$k]['status'] = $v->status; //状态
            $data[$k]['created_at'] = strtotime($v->created_at); //创建时间
            $data[$k]['genre'] = $this->handle_show_status($v->type, $v->status,1); //类型
        }
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 处理订单显示状态
     * @param type 1 买入 2 卖出
     * @param status 订单状态 状态 1 未付款 2 已付款 3 已完成 4 已取消 5 申诉中 6 申述完结
     * @param num 查询源 1订单列表 2订单详情
     */
    private function handle_show_status($type, $status, $num)
    {
        //如果订单已取消，返回false
        if ($status == 4)
            return 7;
        //申述中，申述完结，返回申述中
        if (in_array($status, [5, 6]))
            return 4;
        //订单已付款
        if ($status == 2) {
            if ($type == 1)//买入返回待收币
                return 2;
            return 3;//卖出返回待发币
        }
        //订单已完成，返回已完成
        if ($status == 3)
            return 5;
        //如果源是详情
        if ($num == 2) {
            if ($type == 1)//买入返回未付款
                return 1;
            return 6;//卖出返回 待对方付款60分钟
        }
        //如果源是列表 返回未付款
        return 1;
    }

    /**
     * c2c订单完成.
     * @date 2018/03/24
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function success_order(Request $request)
    {
        $info = $request->all();
        if (empty($info['oid']))
            return respF(1003);
        $real = Recharge::where(['id' => $info['oid'], 'status' => 3])->get();
        if (collect($real)->count() == 0)
            return respF(1015);
        $data = [];
        foreach ($real as $k => $v) {
            $data[$k]['order_no'] = $v->order_no; //订单号
            $data[$k]['nickname'] = $v->seller->nickname; //名称
            $data[$k]['type'] = $v->type ?? null;
            $data[$k]['price'] = sprintf('%.2f', $v->total_price); //总额
            $data[$k]['title'] = $v->rech_order->price_section; //头部卖出
//            $data[$k]['created_at'] = strtotime($v->created_at);//创建时间
            $data[$k]['num'] = sprintf('%.2f', $v->num); //数量
            $data[$k]['mark_no'] = $v->mark_no; //参考号
        }
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * c2c新的提交接口.
     * @date 2018/05/17
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function new_pay_order(Request $request)
    {
        $info = $request->all();
        if ($info['is_custom'] == 1) {
            if (empty($info['type'] || empty($info['uid']) || empty($info['bid']) || empty($info['oid']) || $info['token']))
                return respF(1003);
        } else {
            if (empty($info['total_price']) || empty($info['bid']) || empty($info['num']) || empty($info['oid']) || empty($info['type']) || empty($info['price']) || empty($info['uid']) || empty($info['token'])
            )
                return respF(1003);
        }
        //验证参数
        $real = RechOrder::where(['id' => $info['oid']])->first();
        if ($info['is_custom'] == 1)
            $info['num'] = $real->price_section;
        //不能自己买自己的单
        if ($real->uid == $info['uid']) {
            //不能购买自己发布的广告
            return respF(3022);
        }
        //验证交易限制(已购买用户购买)
        if ($real->trade_limit == 1) {
            //平台有过交易的用户(已完成)
            $trade_order = Recharge::where(['uid' => $info['uid'], 'status' => 3])->first();
            if (collect($trade_order)->count() == 0) {
                //不支持新用户购买
                return respF(3018);
            }
        }
        //验证交易时间
        if ($real->trade_type == 1) {
            //时间区间转为数组
            $trade_time = explode('-', $real->trade_time);
            //当前时间
            $now_time = date('H:i', time());
            //不在区间
            if ($now_time < $trade_time[0] || $now_time > $trade_time[1]) {
                //不在商家指定交易时间内
                return respF(3019);
            }
        }
        //查找用户
        $user = User::find($info['uid']);
        //验证用户实名
        if ($user->real_status != 2) {
            //实名认证未通过
            return respF(2005);
        }
        //查找今日取消订单次数
//        $cancels = Recharge::where(['uid' => $info['uid'], 'status' => 4])
//            ->whereDate('created_at', date('Y-m-d', time()))->get();
//        if ($cancels->count() >= 3) {
//            //今日取消订单次数已达3次，限制购买
//            return respF(3020);
//        }
        if ($info['type'] != $real->type) {
            return respF(1003);
        }
        try {
            DB::beginTransaction();
            if ($info['type'] == 1) {
//            $pay_pass = User::where(['id'=>$info['uid']])->value('pay_pass');
//            if (md5($info['pay_pass']) != $pay_pass) {
//                //return respF(2026);
//                throw new Exception(2026);
//            }
                $type = 2;
                //usdt ID
                $usdt_id = Currency::where('name_en', 'USDT')->value('id');
                //用户usdt资产
                $property = Property::where(['uid' => $info['uid'], 'cid' => $usdt_id])->first();
                //判断资产
                if ($property->balance < $info['num']) {
                    //用户资产不足
                    //return respF(2008);
                    throw new Exception(2008);
                }
                //判断支付方式
                if (collect($user->user_alipay)->count() == 0 && collect($user->user_wechat)->count() == 0) {
                    //请绑定至少一种支付方式
                    //return respF(3016);
                    throw new Exception(3016);
                }
                //冻结用户资产
                $property->decrement('balance', $info['num']);
                $property->increment('blocked', $info['num']);

//                $msg_one = '您的订单已下单成功，请等待对方付款后发币';
//                $msg_two = '您有一个新的订单，请尽快付款';
            } else {
                $type = 1;
//                $msg_one = '您的订单已下单成功，请尽快付款';
//                $msg_two = '您有一个新的订单，请等待对方付款后发币';
            }
            /*if ($real->surplus_num < $info['num']) {
                //return respF(2034);
                throw new Exception(2034);
            }*/
//            $model = new Yunxin\Yunxin();
//            $arr = $model->send_yx_msg($info['uid'], $info['bid'], $msg_one, $msg_two);
            $code = getCode();
            if ($info['is_custom'] == 1) {
                $total_price = $real->price_section * $real->price;
                $num = $real->price_section;
            } else {
                $total_price = $info['total_price'];
                $num = $info['num'];
            }
            $data_info = [
                'uid' => $info['uid'],
                'order_id' => $info['oid'],
                'num' => $num,
                'price' => $real->price,
                'total_price' => $total_price,
                'bid' => $info['bid'],
                'status' => 1,
                'mark_no' => $code,
                'type' => $type,
                'order_no' => get_microtimes(),
            ];
            //dd($data_info);
            //减去广告单剩余数量
            //$real->decrement('surplus_num', $info['num']);
            //增加成交数量
            $real->increment('deal_num', $info['num']);
            //新增法币交易记录
            $result = Recharge::create($data_info);

            $id['id'] = $result->id;
            DB::commit();

            return response()->json(['status' => 1, 'msg' => '下单成功', 'data' => $id]);
        } catch (Exception $e) {
            //回滚
            DB::rollback();
            //接收错误号
            $msg = $e->getMessage();

            return respF($msg);
        }
    }

    /**
     * c2c自定义详情接口.
     *
     * @date 2018/05/17
     *
     * @author lizhenhua
     *
     * @param Request $request
     *
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function pay_info(Request $request)
    {
        $info = $request->all();
        if (empty($info['oid'])) {
            return respF(1003);
        }
        $result = RechOrder::where(['id' => $info['oid']])->select('price', 'uid', 'type')->first();

        if (collect($result)->count() == 0) {
            return respF(1015);
        }
        $data = [
            'price' => sprintf('%.2f', $result->price), //单价//可购买单价
            'bid' => $result->uid,
            'type' => $result->type,
        ];

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * c2c交易密码判断.
     *
     * @date 2018/05/17
     *
     * @author lizhenhua
     *
     * @param Request $request
     *
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function check_pay_word(Request $request)
    {
        $info = $request->all();
        if (empty($info['pay_pass']) || empty($info['uid'])) {
            return respF(1003);
        }
        $result = User::where(['id' => $info['uid']])->first();
        if ($result->pay_pass != md5($info['pay_pass'])) {
            return respF(2026);
        }

        return response()->json(['status' => 1, 'msg' => '成功']);
    }

    /**
     * c2c支付宝订单号.
     * @date 2018/05/18
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function add_alipay_indent(Request $request)
    {
        $info = $request->all();
        if (empty($info['oid']) || empty($info['code']))
            return respF(1003);
        $result = Recharge::where(['id' => $info['oid']])->update(['alipay_indent' => $info['code']]);
        if ($result) {
            return response()->json(['status' => 1, 'msg' => '成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '失败']);
        }
    }

    /**
     * 条例信息.
     * @date 2018/06/1
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function remind(Request $request)
    {
        $info = $request->all();
        if (empty($info['key']))
            return respF(1003);
        $where['key'] = $info['key'];
        $result = Config::where($where)->select('value')->first();
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $result]);
    }

    /**
     * 服务器当前时间.
     * @date 2018/06/4
     * @author lizhenhua
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function now_time(Request $request)
    {
        $result['time'] = time();
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $result]);
    }
}
